package com.hj.sms.common.listener;

import com.aliyuncs.exceptions.ClientException;
import com.hj.common.constant.Constants;
import com.hj.common.constant.RabbitAttribute;
import com.hj.common.exception.BusinessException;
import com.hj.common.util.AliSmsUtils;
import com.hj.common.util.StringUtils;
import com.hj.common.util.UUIDUtils;
import org.aspectj.apache.bcel.classfile.Code;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 监听队列发送短信
 */
@Component
public class SmsListener {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitHandler
    @RabbitListener(queues = RabbitAttribute.SMS_QUEUE)
    public void smsListener(String phone) {
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException("手机号为空");
        }
        String code = UUIDUtils.getRandomNumber(6);
        logger.info("向手机号 : {} , 发送验证码code : {}",phone, code);
        try {
            redisTemplate.opsForHash().put(Constants.SMS_PHONE + phone, "code", code);
            redisTemplate.boundValueOps(phone).expire(60, TimeUnit.SECONDS);
            AliSmsUtils.sendShortMessage(phone,code);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new BusinessException("短信发送失败");
        }
    }
}
